package com.tubang.logistics.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tubang.common.constant.Constants;
import com.tubang.common.util.BeanMapper;
import com.tubang.common.util.GsonQuick;
import com.tubang.common.util.MsgCode;
import com.tubang.common.util.ResultData;
import com.tubang.component.entity.AddressEntity;
import com.tubang.component.service.IAddressService;
import com.tubang.component.util.RequestUtil;
import com.tubang.component.vo.AddressVo;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wsl
 * @since 2017-11-21
 */
@RestController
@RequestMapping("/address")
public class AddressController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IAddressService addressService;

    /**
     * @param
     * @param
     * @return ResultData 返回类型
     * @throws
     * @Title insertOrUpdate
     * @Description 添加或者修改地址
     */
    @PostMapping(value = "insertOrUpdate")
    public ResultData insertOrUpdate(HttpServletRequest request, HttpServletResponse response) {
    	String receivePostJson = RequestUtil.receivePostJson(request);
    	AddressVo form = GsonQuick.toObject(receivePostJson, AddressVo.class);
		try {
			AddressEntity addressEntity = BeanMapper.map(form, AddressEntity.class);
			addressEntity.setUpdateTime(new Date());
			addressService.insertOrUpdate(addressEntity);
			logger.info("[address]<== method[insertOrUpdate],插入的数据为 ：[{}] ", GsonQuick.getGson().toJson(addressEntity));
			return ResultData.result(true);
		} catch (Exception e) {
			logger.error("[address]<== method[insertOrUpdate], 地址查询失败 addressId:[{}]", e.getMessage());
			e.printStackTrace();
			return ResultData.result(false).setData(e);
		}
       
    }

    /**
     * @Description 根据id查询地址
     * @param  id 地址编号
     * @Title selectById
     * @return ResultData
     */
    @GetMapping(value = "selectById")
    public ResultData selectById(@RequestParam(required = true) String id) {
    	
    	logger.info("[address]==> method[selectById],请求addressId：{}", id);
        try {
			AddressEntity addressEntity = addressService.selectById(id);
			if (null != addressEntity) {
			    logger.info("[address]<== method[selectById], 地址查询结果为{}", GsonQuick.getGson().toJson(addressEntity));
			    return ResultData.result(true).setData(addressEntity);
			} else {
			    logger.info("[address]<== method[selectById], 地址查询失败 addressId:[{}]", id);
			    return ResultData.result(true).setMsg(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST_DESC).setCode(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST);
			}
		} catch (Exception e) {
			logger.error("[address]<== method[selectById], 地址查询失败 addressId:[{}]",e.getMessage());
			e.printStackTrace();
			return ResultData.result(false).setData(e);
		}
    }

    /**
     * @param
     * @return ResultData 返回类型
     * @throws
     * @Title selectByUserId
     */
    @GetMapping(value = "selectAddressList")
    public ResultData selectByUserId(AddressVo addressVo) {
    	
        logger.info("[address]==> method[selectAddressList],请求userId：{}", GsonQuick.getGson().toJson(addressVo));
		try {
			AddressEntity addressEntity = BeanMapper.map(addressVo, AddressEntity.class);
			EntityWrapper<AddressEntity> wrapper = new EntityWrapper<>(addressEntity);
			wrapper.eq("enable",true);
			Page<AddressEntity> page = addressService.selectPage(new Page<>(addressVo.getPage(), addressVo.getRows()),wrapper);
			
			int totalCount = addressService.selectCount(wrapper);
			logger.info("[address]<== method[selectAddressList], 查询结果：{}", GsonQuick.getGson().toJson(page));
			return ResultData.result(true).setTotalCount(totalCount).setData(page.getRecords());
		} catch (Exception e) {
			logger.error("[address]<== method[selectAddressList], 查询失败：{}", e.getMessage());
			e.printStackTrace();
			return ResultData.result(false).setData(e);
		}
    }
    
    /**
     * @Description 设置默认地址
     * @param  id 地址编号
     * @Title setDefaultAddress
     * @return ResultData
     */
    @PutMapping(value = "setDefaultAddress")
    public ResultData setDefaultAddress(@RequestParam(required = true) String id) {
    	
    	logger.info("[address]==> method[setDefaultAddress],请求addressId：{}", id);
        try {
        	//获取userid
			AddressEntity addressEntity = addressService.selectById(id);
			if (null != addressEntity) {
				AddressEntity ae= new AddressEntity();
				ae.setUserId(addressEntity.getUserId());
				ae.setDefaultFlag(Constants.DEFAULT_VAULE_ONE);
				EntityWrapper<AddressEntity> ew= new EntityWrapper<>(ae);
				AddressEntity addressDefault = addressService.selectOne(ew);
				if (addressDefault!=null) {
					addressDefault.setDefaultFlag(Constants.DEFAULT_VAULE_ZERO);
					addressDefault.setUpdateTime(new Date());
					addressService.updateById(addressDefault);
				}
				addressEntity.setDefaultFlag(Constants.DEFAULT_VAULE_ONE);
				addressEntity.setUpdateTime(new Date());
				addressService.updateById(addressEntity);
			    return ResultData.result(true);
			} else {
			    logger.info("[address]<== method[setDefaultAddress], 地址查询失败 addressId:[{}]", id);
			    return ResultData.result(true).setMsg(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST_DESC).setCode(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST);
			}
		} catch (Exception e) {
			logger.error("[address]<== method[setDefaultAddress], 地址查询失败 addressId:[{}]",e.getMessage());
			e.printStackTrace();
			return ResultData.result(false).setData(e);
		}
    }

}

	
	
